//
//  MainViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/21.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import MAMapKit
import SnapKit
import AMapSearchKit

class MainViewController: UIViewController, SegueHandlerType {
    
    enum SegueIdentifier: String {
        case preorderSegue
        case webViewSegue
        case returnDetailSegue
        case cancelNoPaySegue
        case orderUnPaySence
        case CoerceEndOrderSegue
        case durationPackageSegue
        case commitOrderSegue
        case ConfirmPaySegue
        case coerceEndDayOrder
        case dayReturnDetailSegue
        case messageSence
        case gotoAuthPageViewSence
        case guideSence
        case gotoGuideIdent
        case appointmentSegue
        case DrivingLicenseSegue
        case ReviewAttentationSegue
        case AttentationRejectSegue
        case shopSeuge
    }
    
    @IBOutlet var statusView: UIView!             //最上面的判断是否交纳押金的条
    @IBOutlet weak var mapView: MAMapView!
    @IBOutlet var preorderView: UIView!
    @IBOutlet var carScrollView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBOutlet weak var carInfoView: UIView!
    
//    @IBOutlet weak var preorderButton: UIButton!

    @IBOutlet weak var goButton: UIButton!
    
    @IBOutlet weak var leftButton: UIButton!
    
    @IBOutlet weak var rightButton: UIButton!
    
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var tipButton: UIButton!
    
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var currentImage: UIImageView!
    
    @IBOutlet var calloutView: UIView!
    @IBOutlet weak var calloutLabel: UILabel!
    
    @IBOutlet weak var locButton: UIButton!
    @IBOutlet weak var centerButton: UIButton!
    
    var gotoOrderBlock: (() -> ())?
    
    var appointDuration = 0
    
    let search = AMapSearchAPI()
    
    var currentAddress = ""
    
    var shortest = 1
    
    var pathPolyLines = [CLLocationCoordinate2D]()
    
    var polyLine: MAPolyline?
    
    let startAnnotation = StartAnnotation()
    
    lazy var geo: Geo? = {
        return Fence.readGeoJson()
    }()
    
    var durationPackageId: String? = nil
    
    var currentCar: CarAnnotation? = nil
    
    var selectedLocation: CLLocationCoordinate2D? = nil
    
    @IBOutlet weak var callCenterConstraint: NSLayoutConstraint!
    @IBOutlet weak var locConstraint: NSLayoutConstraint!
    
    var isSupportPreorder: Bool {
        if let s = slipViewController?.config?.preorderOpenFlag, s == 1 {
            return true
        }
        return false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView.bringSubview(toFront: searchButton)
        mapView.delegate = self
        mapView.config()
        
        search?.delegate = self
        
        showGoButton()
    }
    
    func showGoButton() {
        goButton.isHidden = isSupportPreorder
        leftButton.isHidden = !isSupportPreorder
        rightButton.isHidden = !isSupportPreorder
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        navigationController?.isNavigationBarHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.isNavigationBarHidden = true
        
        //监测是否有订单
        if User.isLogin() {
            
            if User.isAuthentication() {
            
                if User.isPaydeposit() || User.memberType() == 3 || User.isBoundCard() {
                    self.statusView.isHidden = true
                    Order.progressOrder(success: { [weak self] order in
                        if let order = order {
                            self?.goToOrder(progressOrder: order)
                        } else {
                            self?.statusView.isHidden = true
                        }
                    }) { error in
                        p(error)
                    }
                } else {
                    statusView.isHidden = false
                    tipLabel.text = "您当前未缴纳押金,暂无法订车"
                    tipButton.setTitle("去缴纳", for:.normal)
                }
            } else {
                statusView.isHidden = false
                tipLabel.text = "请您在订车前先通过实名认证"
                tipButton.setTitle("去认证", for:.normal)
                if let user = User.info() {
                    switch user.certStep {
                    case 2:
                        tipButton.setTitle("查看", for:.normal)
                        tipLabel.text = "您的身份证审核中无法用车"
                    case 3:
                        tipButton.setTitle("查看", for:.normal)
                        tipLabel.text = "您的身份证被驳回无法用车"
                    default:break
                    }
                }
            }
        } else {
            statusView.isHidden = true
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - IBAction
    
    @IBAction func commitOrder(_ sender: UIButton) {
        let car = selectedCar()
        
        if let anns = mapView.selectedAnnotations as? [MAAnnotation] {
            for a in anns {
                mapView.deselectAnnotation(a, animated: false)
            }
        }
        
        performSegue(.commitOrderSegue, sender: car)
    }
    
    @IBAction func showMenu(_ sender: UIButton) {
        slipViewController?.showMenu()
    }
    
    @IBAction func go(_ sender: UIButton) {
        guard let loc = mapView.userLocation.location else {
            showError("未取得当前位置。")
            return
        }
        
        mapView.setCenter(loc.coordinate, animated: false)
        loadNearbyCarList(selectedNearbyCar: true)
    }
    
    @IBAction func preorderTouchDown(_ sender: UIButton) {
        leftButton.setImage(UIImage(named: "leftButton2"), for: .normal)
        rightButton.setImage(UIImage(named: "rightButton"), for: .normal)
    }
    
    @IBAction func leftButtonTouchDown(_ sender: UIButton) {
        leftButton.setImage(UIImage(named: "leftButton"), for: .normal)
        rightButton.setImage(UIImage(named: "rightButton2"), for: .normal)
    }
    
    func showLogin() {
        let sb = UIStoryboard(name: "UserInfo", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "LoginViewController")
        present(vc, animated: true)
    }
    
    @IBAction func preorder(_ sender: UIButton) {
        guard User.isLogin() else {
            showLogin()
            return
        }
        leftButtonTouchDown(leftButton)
        performSegue(.appointmentSegue, sender: nil)
    }
    
    @IBAction func callCenter(_ sender: UIButton) {
        guard User.isLogin() else {
            showLogin()
            return
        }
        
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: "故障上报", style: .default, handler: { [weak self] action in
            self?.performSegue(.gotoGuideIdent, sender: self)
        }))
        
        actionSheet.addAction(UIAlertAction(title: "联系客服", style: .default, handler: { action in
            if let url = kCallCenter {
                UIApplication.shared.open(url)
            }
        }))
        actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        present(actionSheet, animated: true)
    }
    
    @IBAction func moveUserLocation(_ sender: UIButton) { 
        guard let loc = mapView.userLocation.location else {
            return
        }

        mapView.setCenter(loc.coordinate, animated: true)
        
        UIView.animate(withDuration: 0.25, animations: {
            sender.imageView?.transform = CGAffineTransform(rotationAngle:.pi)
        }) { finish in
            if finish {
                sender.imageView?.transform = CGAffineTransform.identity
            }
        }
    }
    
    @IBAction func userStatus(_ sender: UIButton) {
        
        guard User.isLogin() else {
            showLogin()
            return
        }
        
        guard User.isAuthentication() else {
            if let user = User.info() {
                switch user.certStep {
                case 0:performSegue(.gotoAuthPageViewSence, sender: nil)
                case 1:performSegue(.DrivingLicenseSegue, sender: nil)
                case 2:performSegue(.ReviewAttentationSegue, sender: nil)
                case 3:performSegue(.AttentationRejectSegue, sender: nil)
                default:break
                }
            }
            return
        }
        
        if User.isPaydeposit() || User.memberType() == 3 || User.isBoundCard() {
            gotoOrderBlock?()
        } else {
            let vc = userInfoStory.instantiateViewController(withIdentifier: "DepositInfoViewController")
            if let vc = vc as? DepositInfoViewController {
                vc.page = .timeRent
            }
            
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    @IBAction func searchCar(_ sender: UIButton) {
        func startSearch(_ alert: UIAlertController) {
            guard let text = alert.textFields?.first?.text, !text.isEmpty else {
                XHProgressHUD.showError("请输入你要查找的车牌号")
                return
            }
            
            JZLoading.showLoadingWith(toView: self.view)
            let number = text.replacingOccurrences(of: " ", with: "")
            Car.queryCar(plateNumber: number, success: { [weak self] data in
                JZLoading.hideLoading()
                if let car = data,
                    let lat = Double(car.carLat),
                    let lng = Double(car.carLng) {
                    let ann = CarAnnotation(id: car.carId, icon: car.carIcon)
                    ann.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
                    self?.mapView.addAnnotation(ann)
                    self?.mapView.selectAnnotation(ann, animated: true)
                }
                }, failure: { [weak self] message in
                    JZLoading.hideLoading()
                    self?.showError(message)
            })
        }
        
        func createAlert(_ shortName: String?) -> UIAlertController {
            let alert = UIAlertController(title: "搜索车牌,即可订车", message: nil, preferredStyle: .alert)
            
            alert.addTextField { textField in
                textField.placeholder = "请精确输入您要搜索的车牌号"
                textField.text = shortName
            }
            
            alert.addAction(UIAlertAction(title: "确定", style: .default) { action in
                startSearch(alert)
            })
            
            alert.addAction(UIAlertAction(title: "取消", style: .cancel))
            
            return alert
        }
        
        if let coor = mapView?.userLocation?.location?.coordinate {
            
            JZLoading.showLoadingWith(toView: self.view)
            City.short(location: coor, success: { [weak self] data in
                JZLoading.hideLoading()
                if let name = data?.shortName {
                    self?.present(createAlert(name), animated: true)
                } else {
                    self?.present(createAlert(nil), animated: true)
                }
            }) { [weak self] message in
                JZLoading.hideLoading()
                self?.present(createAlert(nil), animated: true)
            }
        }
    }
    
    @IBAction func messageCenter(_ sender: Any) {
        
        guard User.isLogin() else {
            showLogin()
            return
        }

        performSegue(.messageSence, sender: nil)
    }
    
    // MARK: - custom method
    
    func goToOrder(progressOrder order: Order.ProgressOrder) {
        
        if order.orderType == 1 {   //分时
            if order.forceFlag == 2 {
                gotoOrderBlock = { [weak self] in
                    self?.performSegue(.CoerceEndOrderSegue, sender: order.orderId)
                }
            } else {
                switch order.orderStatus {
                case .reserve:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.preorderSegue, sender: order.orderId)
                    }
                case .cancelNoPay:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.cancelNoPaySegue, sender: order.orderId)
                    }
                case .use:
                    gotoOrderBlock = { [weak self] in
                        self?.statusView.isHidden = false
                        self?.performSegue(.preorderSegue, sender: order.orderId)
                    }
                case .returnCar:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.returnDetailSegue, sender: order.orderId)
                    }
                case .pay:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.returnDetailSegue, sender: order.orderId)
                    }
                case .finish:
                    gotoOrderBlock = { [weak self] in
                        let paramter = ["orderId":order.orderId]
                        self?.performSegue(.orderUnPaySence, sender: paramter)
                    }
                }
            }
        } else if order.orderType == 2 {    //日租
            if order.forceFlag == 2 {
                gotoOrderBlock = { [weak self] in
                    self?.performSegue(.coerceEndDayOrder, sender: order.orderId)
                }
            } else {
                switch order.orderStatus {
                case .reserve:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.ConfirmPaySegue, sender: order.orderId)
                    }
                case .cancelNoPay:
                    break
                case .use:
                    gotoOrderBlock = { [weak self] in
                        self?.statusView.isHidden = false
                        self?.performSegue(.preorderSegue, sender: order.orderId)
                    }
                case .pay, .finish, .returnCar:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(.dayReturnDetailSegue, sender: order.orderId)
                    }
                }
            }
        }
        
        if gotoOrderBlock != nil {
            statusView.isHidden = false
            tipLabel.text = "您有正在进行中的订单"
            tipButton.setTitle("回到订单", for:.normal)
        }
    }
    
    func selectedNearbyCar() {
        guard let ann = mapView.annotations as? [MAPointAnnotation] else {
            self.showError("抱歉，附近暂无可用车辆，请尝试右上角搜索车牌直接订车(1026)")
            return
        }
        
        guard ann.count > 0 else {
            showError("抱歉，附近暂无可用车辆，请尝试右上角搜索车牌直接订车(1026)")
            return
        }
        
        for i in ann {
            if self.shortest == 1 {
                if let a = i as? CarAnnotation, a.isFirst {
                    mapView.selectAnnotation(i, animated: true)
                }
            } else {
                if let a = i as? ParkingAnnotation, a.isFirst {
                    mapView.selectAnnotation(i, animated: true)
                }
            }
        }
    }
    
    func selectedCar() -> Car.Detail? {
        let current = Int(self.carScrollView.contentOffset.x / self.carScrollView.frame.size.width)
        
        guard current < self.carScrollView.subviews.count else {
            return nil
        }
        
        guard let carView = self.carScrollView.subviews[current] as? CarView else {
            return nil
        }
        
        return carView.car
    }
    
    func showPreorderView(_ isUseableDurationPackage: Bool = false) {
        goButton.isHidden = true
        leftButton.isHidden = true
        rightButton.isHidden = true
        
        callCenterConstraint.constant = 230
        locConstraint.constant = 230
        
        view.addSubview(preorderView)
        preorderView.snp.makeConstraints { make in
            make.bottom.equalTo(bottomLayoutGuide.snp.top)
            make.height.equalTo(237)
            make.width.equalTo(340)
            make.centerX.equalTo(view.snp.centerX)
        }
    }
    
    func loadNearbyCarList(selectedNearbyCar: Bool = false) {
        
        let coor = self.mapView.centerCoordinate
        
        Car.nearbyCarList(location: coor, success: { [weak self] data in
            guard let data = data else {
                return
            }
            
            self?.mapView.removeAnnotations(self?.mapView.annotations)
            
            //添加annotation
            var isFirst = true
            for car in data.carList {
                if let lat = Double(car.carLat), let lng = Double(car.carLng) {
                    let ann = CarAnnotation(id: car.carId, icon: car.carIcon)
                    ann.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
                    if isFirst {
                        ann.isFirst = true
                        isFirst = false
                    }
                    self?.mapView.addAnnotation(ann)
                }
            }
            
            isFirst = true
            for parking in data.parkingList {
                if let lat = Double(parking.lat), let lng = Double(parking.lng) {
                    let ann = ParkingAnnotation(id: parking.id, carNum: parking.carNum)
                    ann.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
                    if isFirst {
                        ann.isFirst = true
                        isFirst = false
                    }
                    self?.mapView.addAnnotation(ann)
                }
            }
            
            //最近的停车场或车辆
            self?.shortest = data.shortest
            
            if selectedNearbyCar {
                self?.selectedNearbyCar()
            }
        }) { error in
            p(error)
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segueIdentifier(forSegue: segue) {
        case .preorderSegue:
            if let vc = segue.destination as? PreorderViewController {
                vc.orderId = sender as? String
            }
        case .webViewSegue:
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.regular)
            }
        case .returnDetailSegue:
            if let vc = segue.destination as? ReturnDetailViewController {
                vc.orderId = sender as? String
            }
        case .cancelNoPaySegue:
            if let vc = segue.destination as? CancelOrderPayViewController {
                vc.orderId = sender as? String
            }
        case .orderUnPaySence:
            if let vc = segue.destination as? OrderDetailViewController,
                let sender = sender as?[String : String] {
                vc.orderId = sender["orderId"]!
                vc.page = .debtOrder
            }
        case .CoerceEndOrderSegue:
            if let vc = segue.destination as? CoerceEndOrderViewController {
                vc.orderId = sender as? String
            }
        case .durationPackageSegue:
            if let vc = segue.destination as? DurationPackageListViewController {
                vc.projectTimerentId = selectedCar()?.projectTimerentId
                vc.selectedDurationPackageId = self.durationPackageId
                vc.sourceFlag = 1
                vc.selectedPackageBlock = { id, name in
                    self.durationPackageId = id
                }
            }
        case .commitOrderSegue:
            if let vc = segue.destination as? ConfirmPreorderViewController {
                vc.car = sender as? Car.Detail
                vc.currentAddress = self.currentAddress
            }
        case .ConfirmPaySegue:
            if let vc = segue.destination as? ConfirmPayViewController {
                vc.orderId = sender as? String
            }
        case .coerceEndDayOrder:
            if let vc = segue.destination as? CoerceEndDayOrderController {
                vc.orderId = sender as? String
            }
        case .dayReturnDetailSegue:
            if let vc = segue.destination as? DayReturnDetailViewController {
                vc.orderId = sender as? String
            }
        case .messageSence:
            break
        case .gotoAuthPageViewSence:
            break
        case .guideSence:
            break
        case .gotoGuideIdent:
            break
        case .appointmentSegue:
            break
        case .DrivingLicenseSegue:
            break
        case .ReviewAttentationSegue:
            break
        case .AttentationRejectSegue:
            break
        case .shopSeuge:
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController,
                let url = slipViewController?.config?.dayCouponUrl {
                    vc.page = Page.URL(url)
            }
        }
    }
}

// MARK: - MAMapViewDelegate

extension MainViewController: MAMapViewDelegate {
    
    func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
        if wasUserAction {
            if let ann = mapView.selectedAnnotations {
                if ann.count == 0 {
                    loadNearbyCarList()
                }
            } else {
                loadNearbyCarList()
            }
        } else {
            if let ann = mapView.annotations, ann.count == 0 {
                loadNearbyCarList()
            }
        }
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        let carReuseIndetifier = "car_reuse_indetifier"
        let parkingReuseIndetifier = "parking_reuse_indetifier"
        let startIndetifier = "start_indetifier"
        
        if annotation is MAUserLocation {
            return nil
        }
        
        if annotation is StartAnnotation {
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: startIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: carReuseIndetifier)
            }
            
            annotationView?.image = UIImage(named: "map_center")
            annotationView?.centerOffset = CGPoint(x: 0, y: -24)
            
            return annotationView!
        }
        
        if let ann = annotation as? CarAnnotation {
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: carReuseIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: ann, reuseIdentifier: carReuseIndetifier)
            }
            
            switch ann.icon {
            case 1, 2, 3, 4:
                annotationView?.image = UIImage(named: "red_bag\(ann.icon)")
            default:
                annotationView?.image = UIImage(named: "restaurant")
            }
            
            annotationView?.centerOffset = CGPoint(x: 0, y: -24)
            annotationView?.canShowCallout = false
            
            return annotationView!
        }
        
        if annotation.isKind(of: ParkingAnnotation.self) {
            var annotationView: ParkingAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: parkingReuseIndetifier) as? ParkingAnnotationView
            
            if let ann = annotation as? ParkingAnnotation {
                if annotationView == nil {
                    annotationView = ParkingAnnotationView(annotation: annotation,
                                                           reuseIdentifier: parkingReuseIndetifier,
                                                           num: ann.carNum)
                }
            }
            
            return annotationView!
        }
        
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
        
        currentImage.isHidden = true
        
        if let annotation = view.annotation {
            
            if annotation is MAUserLocation {
                return
            }
            
            selectedLocation = mapView.centerCoordinate
            
            if let ann = annotation as? CarAnnotation {
                Car.detail(carId: ann.id, location: mapView.centerCoordinate, success: { [weak self] car in
                    guard let self = self else {
                        return
                    }
                    
                    guard let car = car else {
                        self.showError("服务器错误！")
                        return
                    }
                    
                    self.carScrollView.removeAllSubviews()
                    self.showPreorderView(car.isUseableDurationPackage == 1)
                    
                    self.carScrollView.contentSize = self.carScrollView.frame.size
                    
                    if let carView = Bundle.main.loadNibNamed("CarView", owner: nil)?.last as? CarView {
                        carView.frame = self.carScrollView.frame
                        carView.setCar(car: car)
                        
                        self.carScrollView.addSubview(carView)
                        self.pageControl.isHidden = true
                    }
                    
                    self.calloutView.center = CGPoint(x: view.bounds.width / 2.0,
                                                      y: -self.calloutView.bounds.height / 2.0)
                    self.calloutLabel.text = "距您\(car.carDistance)m"
                    self.calloutLabel.sizeToFit()
                    self.calloutView.sizeToFit()
                    
                    view.addSubview(self.calloutView)
                }) { [weak self] error in
                    self?.showError(error)
                }
            } else if let ann = annotation as? ParkingAnnotation {
                Car.parkingCarList(
                    parkingLotId: ann.id,
                    location: mapView.centerCoordinate,
                    success: { [weak self] carList in
                    
                    guard let self = self else {
                        return
                    }
                    
                    guard let carList = carList else {
                        self.showError("服务器错误！")
                        return
                    }
                    
                    self.carScrollView.removeAllSubviews()
                    self.showPreorderView(false)
                    
                    let count = carList.count
                    
                    var size = self.carScrollView.frame.size
                    
                    size.width = (kScreenWidth - 20) * CGFloat(count)
                    self.carScrollView.contentSize = size
                    
                    var c = 0
                    for i in carList {
                        var rect = self.carScrollView.frame
                        rect.origin.x = (kScreenWidth - 20) * CGFloat(c)
                        if let carView = Bundle.main.loadNibNamed("CarView", owner: nil, options: nil)?.last as? CarView {
                            carView.frame = rect
                            carView.setCar(car: i)
                            self.carScrollView.addSubview(carView)
                        }
                        c += 1
                    }
                    
                    self.pageControl.numberOfPages = count
                    self.pageControl.isHidden = count < 2
                }) { [weak self] error in
                    self?.showError(error)
                }
            }
            
            //规划步行路线
            let start = selectedLocation!
            let destination = annotation.coordinate
            
            let request = AMapWalkingRouteSearchRequest()
            request.origin = AMapGeoPoint.location(withLatitude: CGFloat(start.latitude),
                                                   longitude: CGFloat(start.longitude))
            request.destination = AMapGeoPoint.location(
                withLatitude: CGFloat(destination.latitude),
                longitude: CGFloat(destination.longitude))
            
            self.search?.aMapWalkingRouteSearch(request)
            
            //起点大头针
            self.startAnnotation.coordinate = start
            self.mapView.addAnnotation(self.startAnnotation)
        }
    }
    
    func mapView(_ mapView: MAMapView!, didDeselect view: MAAnnotationView!) {
        
        if let loc = selectedLocation {
            mapView.setCenter(loc, animated: false)
            selectedLocation = nil
        }
        
        currentImage.isHidden = false
        
        preorderView.removeFromSuperview()
        carScrollView.removeAllSubviews()
        
        mapView.removeOverlays(self.mapView.overlays)
        mapView.removeAnnotation(self.startAnnotation)
        
        search?.cancelAllRequests()
        
        if isSupportPreorder {
            leftButton.isHidden = false
            rightButton.isHidden = false
        } else {
            goButton.isHidden = false
        }
        
        callCenterConstraint.constant = 34
        locConstraint.constant = 34
        
        calloutView.removeFromSuperview()
    }
    
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        guard updatingLocation else {
            return
        }
        
        guard self.currentAddress == "" else {
            return
        }
        
        if let location = userLocation.location {
            let coordinate = location.coordinate
            let request = AMapReGeocodeSearchRequest()
            request.location = AMapGeoPoint.location(
                withLatitude: CGFloat(coordinate.latitude),
                longitude: CGFloat(coordinate.longitude))
            request.requireExtension = true
            self.search?.aMapReGoecodeSearch(request)
            
            if let app = UIApplication.shared.delegate as? AppDelegate {
                app.userLocation = coordinate
            }
        }
    }
    
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        switch overlay {
        case is MAPolyline:
            guard let line = MAPolylineRenderer(overlay: overlay) else {
                return nil
            }
            
            let lineColor = UIColor(red: 255.0 / 255.0, green: 117.0 / 255.0, blue: 23.0 / 255.0, alpha: 1.0)
            line.lineWidth = 5.0
            line.strokeColor = lineColor
            line.fillColor = lineColor
            line.lineDashType = .square
            line.lineJoinType = kMALineJoinRound
            line.lineCapType = kMALineCapRound
            
            return line
        case is MAPolygon:
            guard let gon = MAPolygonRenderer(overlay: overlay) else {
                return nil
            }
            
            gon.lineWidth = 2.0
            gon.strokeColor = UIColor(hexString: "ff7517")
            gon.fillColor = UIColor(hexString: "#ff751723")
            gon.lineJoinType = kMALineJoinRound
            gon.lineCapType = kMALineCapRound
            
            return gon
        case is MACircle:
            let renderer: MACircleRenderer = MACircleRenderer(overlay: overlay)
            renderer.lineWidth = 2.0
            renderer.strokeColor = UIColor(hexString: "ff7517")
            renderer.fillColor = UIColor(hexString: "#ff751723")
            return renderer
        default:
            return nil
        }
    }
    
    func mapView(_ mapView: MAMapView!, mapDidZoomByUser wasUserAction: Bool) {
        guard wasUserAction else {
            return
        }
        
        for i in mapView.overlays ?? [] {
            if i is MAPolygon {
                mapView.remove(i as! MAPolygon)
            } else if i is MACircle {
                mapView.remove(i as! MACircle)
            }
        }
        
        guard mapView.zoomLevel < 13, mapView.zoomLevel > 7 else {
            return
        }
        
        guard let geo = geo else {
            return
        }
        
        for i in geo.list {
            if i.type == "polygon" {
                var points = [CLLocationCoordinate2D]()
                for p in i.coordinates {
                    if let lat = CLLocationDegrees(p[0]), let lon = CLLocationDegrees(p[1]) {
                        points.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
                    }
                }
                let polygon = MAPolygon(coordinates: &points, count: UInt(points.count))
                mapView.add(polygon)
            } else if i.type == "radius" {
                guard let first = i.coordinates.first else {
                    return
                }
                
                if let lat = CLLocationDegrees(first[0]), let lon = CLLocationDegrees(first[1]) {
                    let center = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                    let circle = MACircle(center: center, radius: i.radiusNum)
                    mapView.add(circle)
                }
            }
        }
    }
}

// MARK: - AMapSearchDelegate

extension MainViewController: AMapSearchDelegate {

    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {
        if response.count > 0 {
            
            pathPolyLines.removeAll()
            
            guard let path = response.route.paths.first else {
                return
            }
            
            for step in path.steps {
                if let loc = step.polyline?.components(separatedBy: ";") {
                    for i in loc {
                        let lays = i.components(separatedBy: ",")
                        if let lat = CLLocationDegrees(lays[1]), let lng = CLLocationDegrees(lays[0]) {
                            let location = CLLocationCoordinate2D(latitude: lat, longitude: lng)
                            pathPolyLines.append(location)
                        }
                    }
                }
            }
            
            if let poly = MAPolyline(coordinates: &pathPolyLines, count: UInt(pathPolyLines.count)) {
                mapView.add(poly)
                let insets = UIEdgeInsets(top: 100, left: 40, bottom: preorderView.frame.height + 40, right: 40)
                mapView.showOverlays([poly], edgePadding: insets, animated: true)
            }
        }
    }
    
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        if response.regeocode == nil {
            return
        }
        
        if let address = response.regeocode.formattedAddress {
            currentAddress = address
        }
    }
}

// MARK: - UIScrollViewDelegate

extension MainViewController: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let current = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = current
        
        guard current < scrollView.subviews.count else {
            return
        }
    }
}
